package ObjectOutputStream;

import java.io.*;
import java.util.ArrayList;

public class Text {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student s1 = new Student("于飞正", 23);
        Student s2 = new Student("杨昊", 21);
        Student s3 = new Student("陈志伟", 21);
        Student s4 = new Student("袁晓强", 21);
        ArrayList<Student> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("after_buy\\objWrite.text"));
        /*oos.writeObject(s1);
        oos.writeObject(s2);
        oos.writeObject(s3);
        oos.writeObject(s4);*/
        oos.writeObject(list);
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("after_buy\\objWrite.text"));
        /*Student o1 = (Student) ois.readObject();
        Student o2 = (Student) ois.readObject();
        Student o3 = (Student) ois.readObject();
        Student o4 = (Student) ois.readObject();
        System.out.println(o1);
        System.out.println(o2);
        System.out.println(o3);
        System.out.println(o4);*/
        //优化
        /*try{
            while(true) {
                Student o1 = (Student) ois.readObject();
                System.out.println(o1);
            }
        } catch (EOFException e) {//EOFException当数据读取结束，而继续往下读取时，他就会报错
            System.out.println("数据读取完毕");
        }*/
        //再次优化
        //将数据写到一个集合容器中，值需要读取集合对象即可
        ArrayList<Student> obj = (ArrayList<Student>)ois.readObject();
        //直接遍历集合
        for ( Student s: obj) {
            System.out.println(s);
        }
    }
}
